const App = getApp()
const util = require('../../../utils/util.js')
// 上传图片
let uploadImage = require('../../../utils/uploadFile.js');
Page({
  data: {
    LicenseJSON: {

    },
    car: {},
    imgList: {
      tempFilePaths: [],
      imgList: []
    },
    indexs: 0,
    carlist: [],

    list: [],
    show: !0,
    form: {
      id: 0,
      userId: '',
      carAreaCode: '冀',
      carAreaNo: '',
      carModelId: '',
      purchaseTime: 1,
      // displacement: '',
      // displacementUnit: 'T',
      miles: '',
      linkman: '',
      phone: '',
    },
    msg: {
      carAreaNo: '请输入车牌号',
      displacement: '请输入排量',
      miles: '请输入行驶里程',
      linkman: '请输入联系人',
      phone: '请输入联系电话'
    },
    units: [{
      unit: 'T',
      checked: true
    }, {
      unit: 'L'
    }],
    array: ['美国', '中国', '巴西', '日本'],
  },
  onLoad(e) {
    if (e.id==1){
      this.setData({
        scxsz:true
      })
    }


    let firstMenu = wx.getStorageSync('firstMenu')
    let secondMenu = wx.getStorageSync('secondMenu')
    let thirdMenu = wx.getStorageSync('thirdMenu')
    let userId = wx.getStorageSync('userId')
    let date = util.formatTime(new Date()).date

    this.setData({
      'form.userId': userId,
      'form.carModelId': thirdMenu.id,
      'form.purchaseTime': date,
      car: firstMenu.name + ' ' + secondMenu.name + ' ' + thirdMenu.name
    })

    if (e.id) {
      this.setData({
        car: "",
      })
    }

    this.getCarCode()

  },
  bindDateChange(e) { // 购车日期
    this.setData({
      'form.purchaseTime': e.detail.value
    })
  },
  getCarCode() {
    App.HttpService.getCarCode().then(res => {
      let data = res.data.data

      this.setData({
        list: data
      })

    })
  },
  chooseCode(e) { // 车牌号第一个字
    let {
      code
    } = e.currentTarget.dataset
    this.setData({
      'form.carAreaCode': code,
      showModalStatus: false
    })
  },
  setModalStatus(e) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData({
        showModalStatus: true
      })
    }
    setTimeout(function() {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData({
          showModalStatus: false
        })
      }
    }.bind(this), 100)
  },
  radioChange(e) {
    this.setData({
      'form.displacementUnit': e.detail.value
    })
  },
  inputBlur(e) { // 失去焦点时间
    let form = this.data.form
    let {
      key
    } = e.currentTarget.dataset
    let {
      value
    } = e.detail

    for (var i in form) {
      if (i == key) {
        this.setData({
          ['form.' + key]: value
        })
      }
    }
  },
  liang: function(e) {

    console.log(e.detail.value)
    var a = e.detail.value;
    a = a.toUpperCase();
    console.log(a)
    this.setData({
      'form.carAreaNo': a
    })
  },
  submitForm() { // 保存
    let {
      form,
      msg,
      license = this.data.s
    } = this.data


    for (var i in form) {
      if (form[i] === '') {
        wx.showToast({
          title: "请提交完整数据",
          image: '../../../assets/images/warning.png',
          duration: 1500
        })
        return false
      }
    }

    App.HttpService.carSave(form).then(res => {
      let data = res.data
      if (data.code == 200) {
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1000
        })
    
        wx.removeStorageSync('firstMenu')
        wx.removeStorageSync('secondMenu')
        wx.removeStorageSync('thirdMenu')
        var pages = getCurrentPages()
        if (pages.length > 1) {
          var mg = pages.length-1
          var prePage = pages[pages.length - mg ]
          prePage.onLoad()
        }
        //查询默认车辆
        this.getDefault();

        // wx.navigateTo({
        //   url: '/pages/product/package/index',
        // })
        // wx.navigateBack({
        //   delta: 4
        // })


      } else {
        wx.showModal({
          title: '提示',
          content: data.msg,
          showCancel: false
        })
      }
    })
  },



  getDefault() { // 获取默认车辆
    let userId = wx.getStorageSync('userId')
    let agent = wx.getStorageSync('agent')
    App.HttpService.getDefault({
      userId: userId
    }).then(res => {
      let data = res.data
      if (data.code == 200) {
        if (JSON.stringify(data.data.carInfo) != '{}') {
          let carInfo = data.data.carInfo
          let carModel = data.data.carModel
          let info = carInfo.brandName + ' ' + carInfo.factoryName + ' ' + carInfo.modelName

                   

          let defaultCar = {
            carInfo: info,
            carId: carModel.id, // 默认车辆id
            carModelId: carModel.carModelId, // 车辆 车型三级id
            carFactoryId: carInfo.factoryId, // 车辆 车系二级id
            miles: carModel.miles,
            linkman: carModel.linkman,
            phone: carModel.phone,
            carCode: carModel.carAreaCode + carModel.carAreaNo,
            brandId: carInfo.brandId
          }
          wx.setStorageSync('defaultCar', defaultCar)
          this.setData({
            defaultCar: defaultCar,

          })
          wx.navigateTo({
            url: '/pages/product/package/index',
          })

        } else {

        }
      }
    })
  },

  shangchuan: function(e) {
    console.log(e)
  },

  joinPicture(e) { // 添加图片




    let imgList = this.data.imgList
    let that = this;
    let tempFilePaths = imgList.tempFilePaths
    wx.showActionSheet({
      itemList: ["从相册中选择", "拍照"],
      itemColor: "#333",
      success: function(res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            that.chooseWxImage("album", tempFilePaths)
          } else if (res.tapIndex == 1) {
            that.chooseWxImage("camera", tempFilePaths)
          }
        }
      }
    })
  },
  chooseWxImage(type, list) {
    let img = list
    let len = img.length
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: [type],
      success: function(res) {
        let addImg = res.tempFilePaths
        let addLen = addImg.length
        let addAray = []
        if ((len + addLen) > 3) {
          for (let i = 0; i < (addLen - len); i++) {
            addAray.push(addImg[i])
          }
        } else {
          for (let j = 0; j < addLen; j++) {
            addAray.push(addImg[j])
          }
        }
        that.upload(addAray)
      },
    })
  },
  upload(img) {
    // 图片上传oss

    let that = this
    that.chuantu(img);


  },


  //本地参数测试
  gao: function() {

    this.setData({
      LicenseJSON: {
        address: "河北省沧州市泊头市寺门村镇杨码头村2号",
        carBrand: "哈弗牌CC6460UM07A",
        carNumber: "LGWEF5A52JH006288",
        carType: "小型普通客车",
        engineNo: "62361122",
        licensePlateNumber: "冀J5D2W5",
        name: "李洪旺",
        registerTime: "20180202",
        sendTime: "20180202",
        status: 0,
        useFor: "非营运",
      },
      carlist: [{
          car_year_name: "2018款",
          factory_name: "哈弗H6 Coupe",
          id: 32858,
          model_name: "2018款 红标 1.5T 自动两驱超豪型",
          name: "哈弗",
          nametext: 2018,
        },
        {
          car_year_name: "2013款",
          factory_name: "哈弗H6 Coupe",
          id: 328566,
          model_name: "20199款 红标 1.5T 自动两驱超豪型",
          name: "哈弗",
          nametext: 2018,

        }
      ]
    })

    var d = this.data.LicenseJSON


    // 车牌归属地
    var di = d.licensePlateNumber.substr(0, 1);
    // 车牌号
    var hao = d.licensePlateNumber.substr(1);
    // 车主姓名
    var name = d.name
    // 购车时间
    var gshijian = d.registerTime
    var valDate = gshijian.substring(0, 4) + "-" + gshijian.substring(4, 6) + "-" + gshijian.substring(6, 8);
    // 汽车品牌
    var cpinpai = d.carBrand
    var clid = this.data.carlist[0].id

  
    this.setData({
      // 归属地
      'form.carAreaCode': di,
      // 车牌号
      'form.carAreaNo': hao,
      // 联系人姓名
      'form.linkman': name,
      // 购车时间
      'form.purchaseTime': valDate,
      //车型
      // 车辆的id
      'form.carModelId': clid
      // car: cpinpai
      // 行驶证信息

    })




  },

  //识别图片
  chuantu: function(e) {


    var _this = this
    wx.showLoading({
      title: "信息识别中...",
      mask: true
    })
    console.log(e)

    wx.getFileSystemManager().readFile({
      filePath: e[0], // 选择图片返回的相对路径
      encoding: 'base64', // 编码格式
      success: res => { // 成功的回调
        console.log('66666' + res.data)
        App.HttpService.ceshisss({
          path: res.data,
          userId: wx.getStorageSync("userId"),
          sellerId: wx.getStorageSync('agent').id
        }).then(res => {
         
          wx.hideLoading()
          // var d = res.data.data.LicenseJSON

          if (res.data.code == 200) {
            var d = res.data.data.LicenseJSON   
            //赋值给
              _this.setData({
                carlist: res.data.data.carModels
              })
            wx.showToast({
              title: '识别成功',
              icon: 'success',
              duration: 2000
            })
          

            // 车牌归属地
            var di = d.licensePlateNumber.substr(0, 1);
            // 车牌号
            var hao = d.licensePlateNumber.substr(1);
            // 车主姓名
            var name = d.name
            // 购车时间
            var gshijian = d.registerTime
            var valDate = gshijian.substring(0, 4) + "-" + gshijian.substring(4, 6) + "-" + gshijian.substring(6, 8);
            // 汽车品牌
            var cpinpai = d.carBrand
            // 车辆首位id
            var clid = this.data.carlist[0].id


            _this.setData({
              // 归属地
              'form.carAreaCode': di,
              // 车牌号
              'form.carAreaNo': hao,
              // 联系人姓名
              'form.linkman': name,
              // 购车时间
              'form.purchaseTime': valDate,
              //车型
              // 车辆的id
              'form.carModelId': clid
              // car: cpinpai
              // 行驶证信息

            })

          } else  {
         
            wx.showToast({
              title: res.data.msg,
              icon: 'loading',
              duration: 2000
            })
          }
          console.log("上传图片的返回", res)
        })
      }
    })

  

  },
  //手机号
  shoujih: function(e) {
    console.log(e.detail.value)
    this.setData({
      "form.phone": e.detail.value
    })
  },

  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)

    var cid = this.data.carlist[e.detail.value].id

    this.setData({
      indexs: e.detail.value,
      // 车辆的id
      'form.carModelId': cid
    })
  },


})